﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Forms;
using SmartWallpaperChanger;
using SmartWallpaperChanger.Properties;

namespace SmartWallpaperChanger
{
    public class DirectoryObserver : IDisposable
    {
        private readonly WallpaperList wallpapers;
        private readonly FileSystemWatcher watcher;

        public WallpaperList Wallpapers
        {
            get { return wallpapers; }
        }

        /// <summary>
        /// Initializes a new DirectoryObserver instance.
        /// </summary>
        public DirectoryObserver()
        {
            wallpapers = new WallpaperList();

            watcher = new FileSystemWatcher();
            watcher.Created += watcher_FileCreated;
            watcher.Deleted += watcher_Deleted;
            watcher.Path = Settings.Default.ObservedFolder;
            watcher.EnableRaisingEvents = true;

            BuildWallpaperList();
        }

        private void watcher_Deleted(object sender, FileSystemEventArgs e)
        {
            wallpapers.RemoveWallpaper(e.FullPath);
        }

        private void watcher_FileCreated(object sender, FileSystemEventArgs e)
        {
            wallpapers.AddWallpaper(e.FullPath);
        }

        /// <summary>
        /// Initializes wallpaper list.
        /// </summary>
        private void BuildWallpaperList()
        {
            try
            {
                wallpapers.ClearWallpapers();
                ParseFolder();
            }
            catch { }
        }

        /// <summary>
        /// Parses a folder for images.
        /// </summary>
        private void ParseFolder()
        {
            try
            {
                string[] files = Directory.GetFiles(Settings.Default.ObservedFolder, "*.*", SearchOption.AllDirectories);
                
                foreach (string file in files)
                {
                    wallpapers.AddWallpaper(file);
                }
            }
            catch { }
        }


        public void Dispose()
        {
            watcher.Dispose();
        }
    }
}
